//
//  WFCUFriendInformationVC.m
//  WFChatUIKit
//
//  Created by 0000 on 2024/5/24.
//  Copyright © 2024 Tom Lee. All rights reserved.
//

#import "WFCUFriendInformationVC.h"
#import <SDWebImage/SDWebImage.h>
#import <WFChatClient/WFCChatClient.h>
#import "WFCUMessageListViewController.h"
#import "MBProgressHUD.h"
#import "WFCUMyPortraitViewController.h"
#import "WFCUVerifyRequestViewController.h"
#import "WFCUGeneralModifyViewController.h"
#import "WFCUVideoViewController.h"
#import "WFCUMultiVideoViewController.h"
#if WFCU_SUPPORT_VOIP
#import <WFAVEngineKit/WFAVEngineKit.h>
#endif
#import "UIFont+YH.h"
#import "UIColor+YH.h"
#import "WFCUConfigManager.h"
#import "WFCUUserMessageListViewController.h"
#import "WFCUImage.h"
#import "WFCUProfileMoreTableViewController.h"
#import "MWPhotoBrowser.h"
#import "WFCUOrganizationViewController.h"
#import "WFCUOrganizationCache.h"
#import "WFCUOrganization.h"
#import "WFCUEmployee.h"
#import "WFCUOrgRelationship.h"
#import "WFCUUtilities.h"
#import "WFCUEmployeeEx.h"
#import "WFCUFCircleVC.h"
#import "MomentViewController.h"

#import "YGExtendChain.h"

@interface WFCUFriendInformationVC ()<UITableViewDelegate, UITableViewDataSource, MWPhotoBrowserDelegate>
@property (strong, nonatomic)UIImageView *portraitView;
@property (strong, nonatomic)UILabel *aliasLabel;
@property (strong, nonatomic)UILabel *displayNameLabel;
@property (strong, nonatomic)UILabel *userNameLabel;
@property (strong, nonatomic)UILabel *starLabel;
@property (strong, nonatomic)UITableViewCell *headerCell;


@property (strong, nonatomic)UITableViewCell *sendMessageCell;
@property (strong, nonatomic)UITableViewCell *voipCallCell;
@property (strong, nonatomic)UITableViewCell *addFriendCell;
@property (strong, nonatomic)UITableViewCell *momentCell;
@property (strong, nonatomic)UITableViewCell *moreCell;
@property (nonatomic, strong)UITableViewCell *userMessagesCell;

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray  *cells;
@property (nonatomic, strong)NSMutableArray<UITableViewCell *> *headerCells;

@property (nonatomic, strong)WFCCUserInfo *userInfo;

@property(nonatomic, strong)NSArray<NSNumber *> *organizationIds;

@end

@implementation WFCUFriendInformationVC


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = WFCString(@"UserInfomation");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoUpdated:) name:kUserInfoUpdated object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onEmployeeExUpdated:) name:kEmployeeExUpdated object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onOrganizationUpdated:) name:kOrganizationUpdated object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFriendListUpdated:) name:kFriendListUpdated object:nil];
    
    self.userInfo = [[WFCCIMService sharedWFCIMService] getUserInfo:self.userId refresh:YES];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    if (@available(iOS 15, *)) {
        self.tableView.sectionHeaderTopPadding = 0;
    }
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"..." style:UIBarButtonItemStyleDone target:self action:@selector(onRightBtn:)];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
    
    [self loadOrganizationData:YES];
    
    [self loadData];
}

- (void)loadOrganizationData:(BOOL)refresh {
    WFCUEmployeeEx *employeeEx = [[WFCUOrganizationCache sharedCache] getEmployeeEx:self.userId refresh:refresh];
    if(employeeEx.relationships.count) {
        NSMutableArray<NSNumber *> *arr = [[NSMutableArray alloc] init];
        [employeeEx.relationships enumerateObjectsUsingBlock:^(WFCUOrgRelationship * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if(obj.bottom) {
                [arr addObject:@(obj.organizationId)];
            }
        }];
        self.organizationIds = [arr mutableCopy];
    }
}

- (void)onFriendListUpdated:(NSNotification *)notification {
    [self loadData];
}

- (void)onUserInfoUpdated:(NSNotification *)notification {
    NSArray<WFCCUserInfo *> *userInfoList = notification.userInfo[@"userInfoList"];
    for (WFCCUserInfo *userInfo in userInfoList) {
        if ([self.userId isEqualToString:userInfo.userId]) {
            self.userInfo = userInfo;
            [self loadData];
            break;
        }
    }
}

- (void)onEmployeeExUpdated:(NSNotification *)notification {
    NSString *employeeId = notification.object;
    if([employeeId isEqualToString:self.userId]) {
        [self loadOrganizationData:NO];
        [self.tableView reloadData];
    }
}

- (void)onOrganizationUpdated:(NSNotification *)notification {
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    keyWindow.tintAdjustmentMode = UIViewTintAdjustmentModeAutomatic;
    [keyWindow tintColorDidChange];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)onRightBtn:(id)sender {
    __weak typeof(self)ws = self;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [actionSheet addAction:actionCancel];
    
    if ([[WFCCIMService sharedWFCIMService] isMyFriend:self.userId]) {
        UIAlertAction *deleteFriendAction = [UIAlertAction actionWithTitle:WFCString(@"DeleteFriend") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
            hud.label.text = WFCString(@"Processing");
            [hud showAnimated:YES];
            
            [[WFCCIMService sharedWFCIMService] deleteFriend:ws.userId success:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [hud hideAnimated:YES];
                    
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                    hud.mode = MBProgressHUDModeText;
                    hud.label.text = WFCString(@"ProcessDone");
                    //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                    [hud hideAnimated:YES afterDelay:1.f];
                });
            } error:^(int error_code) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [hud hideAnimated:YES];
                    
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                    hud.mode = MBProgressHUDModeText;
                    hud.label.text = WFCString(@"ProcessFailure");
                    //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                    [hud hideAnimated:YES afterDelay:1.f];
                });
            }];
        }];
        
        [actionSheet addAction:deleteFriendAction];
    } else {
        UIAlertAction *addFriendAction = [UIAlertAction actionWithTitle:WFCString(@"AddFriend") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            WFCUVerifyRequestViewController *vc = [[WFCUVerifyRequestViewController alloc] init];
            vc.userId = ws.userId;
            vc.sourceType = ws.sourceType;
            vc.sourceTargetId = ws.sourceTargetId;
            [ws.navigationController pushViewController:vc animated:YES];
        }];
        [actionSheet addAction:addFriendAction];
    }
    
    
    if ([[WFCCIMService sharedWFCIMService] isBlackListed:self.userId]) {
        UIAlertAction *addFriendAction = [UIAlertAction actionWithTitle:WFCString(@"RemoveFromBlacklist") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
            hud.label.text = WFCString(@"Processing");
            [hud showAnimated:YES];
            
            [[WFCCIMService sharedWFCIMService] setBlackList:ws.userId isBlackListed:NO success:^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessDone");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            } error:^(int error_code) {
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessFailure");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            }];
        }];
        [actionSheet addAction:addFriendAction];
    } else if (self.userInfo.type == 0) {  //Only normal user can add to blacklist, robot user not allowed.
        UIAlertAction *addFriendAction = [UIAlertAction actionWithTitle:WFCString(@"Add2Blacklist") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
            hud.label.text = WFCString(@"Processing");
            [hud showAnimated:YES];
            
            [[WFCCIMService sharedWFCIMService] setBlackList:ws.userId isBlackListed:YES success:^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessDone");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            } error:^(int error_code) {
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessFailure");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            }];
        }];
        [actionSheet addAction:addFriendAction];
    }
    
    
    UIAlertAction *aliasAction = [UIAlertAction actionWithTitle:WFCString(@"SetAlias") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ws setFriendNote];
    }];
    [actionSheet addAction:aliasAction];
    
    if ([[WFCCIMService sharedWFCIMService] isMyFriend:self.userId]) {
        if ([[WFCCIMService sharedWFCIMService] isFavUser:self.userId]) {
            UIAlertAction *cancelStarAction = [UIAlertAction actionWithTitle:WFCString(@"Unstar") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [ws setFavUser];
            }];
            [actionSheet addAction:cancelStarAction];
        } else {
            UIAlertAction *setStarAction = [UIAlertAction actionWithTitle:WFCString(@"Star") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                [ws setFavUser];
            }];
            [actionSheet addAction:setStarAction];
        }
    }
    
    
    [self presentViewController:actionSheet animated:YES completion:nil];
}

- (void)loadData {
    self.cells = [[NSMutableArray alloc] init];
    
    self.sendMessageCell = nil;
    self.voipCallCell = nil;
    self.addFriendCell = nil;
    self.momentCell = nil;
    self.moreCell = nil;
    self.userMessagesCell = nil;
    
    self.headerCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    for (UIView *subView in self.headerCell.contentView.subviews) {
        [subView removeFromSuperview];
    }
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    self.portraitView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 14, 58, 58)];
    
    self.portraitView.layer.cornerRadius = 10 ;
    self.portraitView.layer.masksToBounds = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onViewPortrait:)];
    [self.portraitView addGestureRecognizer:tap];
    self.portraitView.userInteractionEnabled = YES;
    
    
    [self.portraitView sd_setImageWithURL:[NSURL URLWithString:[self.userInfo.portrait stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage: [WFCUImage imageNamed:@"PersonalChat"]];
    
    NSString *alias = [[WFCCIMService sharedWFCIMService] getFriendAlias:self.userId];
    if (alias.length) {
        self.aliasLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 8, width - 64 - 8, 21)];
        self.aliasLabel.text = alias;
        
        self.displayNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 32, width - 94 - 8, 21)];
        self.displayNameLabel.text = self.userInfo.displayName;
        
        self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 60, width - 94 - 8, 11)];
        self.userNameLabel.text = [NSString stringWithFormat:@"TL畅聊号:%@", self.userInfo.name];
        self.userNameLabel.font = [UIFont systemFontOfSize:12];
        self.userNameLabel.textColor = [UIColor grayColor];
        
        
        
        self.userNameLabel.textColor = [UIColor colorWithHexString:@"#8D8B9B"];
        
        NSString *str = [NSString stringWithFormat:@"TL畅聊ID:%@", self.userInfo.name];
        if (self.userInfo.extra.length > 1) {
            
            NSDictionary *dic =  [self.userInfo.extra jk_JSONStringWithDictionary];
     
            NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str attributes:@{}];
            [att addAttribute:NSForegroundColorAttributeName value:[[dic handleNullObjectForKey:@"isVip"] intValue] == 1 ? [UIColor colorWithHexString:@"#FFA332"] : [UIColor colorWithHexString:@"#8D8B9B"] range:NSMakeRange(str.length - self.userInfo.name.length ,   self.userInfo.name.length )];

            self.userNameLabel.attributedText = att ; ///[NSString stringWithFormat:@"TL畅聊号:%@", self.userInfo.name];
            ///
        } else {
            self.userNameLabel.text = str;
        }

        
        
    } else {
        self.aliasLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        
        self.displayNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 23, width - 94 - 8, 21)];
        self.displayNameLabel.text = self.userInfo.displayName;
        self.displayNameLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleMedium size:20];
        
        self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 50, width - 94 - 8, 21)];
        self.userNameLabel.text = [NSString stringWithFormat:@"TL畅聊号:%@", self.userInfo.name];
        self.userNameLabel.font = [UIFont systemFontOfSize:12];
        self.userNameLabel.textColor = [UIColor grayColor];
        
        
        self.userNameLabel.textColor = [UIColor colorWithHexString:@"#8D8B9B"];
        
        NSString *str = [NSString stringWithFormat:@"TL畅聊ID:%@", self.userInfo.name];
        if (self.userInfo.extra.length > 1) {
            
            NSDictionary *dic =  [self.userInfo.extra jk_JSONStringWithDictionary];
     
            NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str attributes:@{}];
            [att addAttribute:NSForegroundColorAttributeName value:[[dic handleNullObjectForKey:@"isVip"] intValue] == 1 ? [UIColor colorWithHexString:@"#FFA332"] : [UIColor colorWithHexString:@"#8D8B9B"] range:NSMakeRange(str.length - self.userInfo.name.length ,   self.userInfo.name.length )];

            self.userNameLabel.attributedText = att ; ///[NSString stringWithFormat:@"TL畅聊号:%@", self.userInfo.name];
            ///
        } else {
            self.userNameLabel.text = str;
        }
        
    }
    
//    if ([[WFCCIMService sharedWFCIMService] isFavUser:self.userId]) {
//        self.starLabel = [[UILabel alloc] initWithFrame:CGRectMake(width - 16 - 20, self.displayNameLabel.frame.origin.y, 20, 20)];
//        self.starLabel.text = @"☆";
//        self.starLabel.font = [UIFont systemFontOfSize:18];
//        self.starLabel.textColor = [UIColor yellowColor];
//        
//        [self.headerCell.contentView addSubview:self.starLabel];
//    }
    
    [self.headerCell.contentView addSubview:self.portraitView];
    [self.headerCell.contentView addSubview:self.displayNameLabel];
    [self.headerCell.contentView addSubview:self.userNameLabel];
    [self.headerCell.contentView addSubview:self.aliasLabel];
    self.headerCells = [NSMutableArray new];
    [self.headerCells addObject:self.headerCell];
    [self.cells addObject:self.headerCells];
    
    
    UITableViewCell *alisaCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"setAlisa"];
    alisaCell.accessoryType = UITableViewCellAccessoryNone;
    alisaCell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 16 - 60, 50)];
    [btn setTitle:WFCString(@"备注名") forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
    [btn addTarget:self action:@selector(setFriendNote) forControlEvents:UIControlEventTouchUpInside];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [alisaCell.contentView addSubview:btn];
    [self showSeparatorLine:alisaCell];

    [self.cells addObject:@[alisaCell].mutableCopy];

    
    UITableViewCell *cell2Section = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2Section"];

    
    UIButton *cell2btn = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 16 - 60, 50)];
    [cell2btn setTitle:WFCString(@"Silent") forState:UIControlStateNormal];
    [cell2btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cell2btn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
//    [cell2btn addTarget:self action:@selector(onSwitch4:) forControlEvents:UIControlEventTouchUpInside];
    cell2btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [cell2Section.contentView addSubview:cell2btn];
    
    WFCCConversation *con = [WFCCConversation conversationWithType:Single_Type target:self.userId line:0];
    
    WFCCConversationInfo *info = [[WFCCIMService sharedWFCIMService] getConversationInfo:con];

    
    UISwitch *valueSwitch = [[UISwitch alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 66, 8, 40, 40)];
    [cell2Section.contentView addSubview:valueSwitch];
    [valueSwitch addTarget:self action:@selector(onSwitch4:) forControlEvents:UIControlEventValueChanged];
    valueSwitch.onTintColor = [UIColor colorWithHexExtendString:@"#016EFF"];
    valueSwitch.on = info.isSilent ;
    
    
    UITableViewCell *cell2Section1 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell2Section"];
//    alisaCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    UIButton *cell2btn1 = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 16 - 60, 50)];
    [cell2btn1 setTitle:WFCString(@"PinChat") forState:UIControlStateNormal];
    
    [cell2btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cell2btn1.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
//    [cell2btn addTarget:self action:@selector(setFriendNote) forControlEvents:UIControlEventTouchUpInside];
    cell2btn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [cell2Section1.contentView addSubview:cell2btn1];
    
    UISwitch *valueSwitch1 = [[UISwitch alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 66, 8, 40, 40)];
    [cell2Section1.contentView addSubview:valueSwitch1];
    [valueSwitch1 addTarget:self action:@selector(setFavUser:) forControlEvents:UIControlEventValueChanged];
//    valueSwitch1.on = [[WFCCIMService sharedWFCIMService] isFavUser:self.userId];
    valueSwitch1.onTintColor = [UIColor colorWithHexExtendString:@"#016EFF"];
    valueSwitch1.on = info.isTop;
    
    
    [self.cells addObject:@[cell2Section,cell2Section1].mutableCopy];

    
    
    
    UITableViewCell *cell3Section1 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell3Section1"];
    cell3Section1.accessoryType = UITableViewCellAccessoryNone;
    cell3Section1.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];

    UIButton *cell3btn1 = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 16 - 60, 50)];
    [cell3btn1 setTitle:WFCString(@"ClearChatHistory") forState:UIControlStateNormal];
    [cell3btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cell3btn1.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
    [cell3btn1 addTarget:self action:@selector(ClearChatHistory) forControlEvents:UIControlEventTouchUpInside];
    cell3btn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [cell3Section1.contentView addSubview:cell3btn1];
    
    
    
    UITableViewCell *cell3Section2 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell3Section1"];
    cell3Section2.accessoryType = UITableViewCellAccessoryNone;
    cell3Section2.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];

    UIButton *cell3btn2 = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 16 - 60, 50)];
    [cell3btn2 setTitle:WFCString(@"设置当前聊天背景") forState:UIControlStateNormal];
    [cell3btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cell3btn2.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
//    [cell2btn addTarget:self action:@selector(setFriendNote) forControlEvents:UIControlEventTouchUpInside];
    cell3btn2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [cell3Section2.contentView addSubview:cell3btn2];
    
    
    [self.cells addObject:@[cell3Section1,cell3Section2].mutableCopy];

    
    UITableViewCell *cell4Section1 = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell4Section1"];
 
    UIButton *cell4btn2 = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 16 - 60, 50)];
    [cell4btn2 setTitle:WFCString(@"加入黑名单") forState:UIControlStateNormal];
    [cell4btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cell4btn2.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
//    [cell4btn2 addTarget:self action:@selector(setFriendNote) forControlEvents:UIControlEventTouchUpInside];
    cell4btn2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [cell4Section1.contentView addSubview:cell4btn2];
    
    
    UISwitch *valueSwitch2 = [[UISwitch alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 66, 8, 40, 40)];
    [cell4Section1.contentView addSubview:valueSwitch2];
    [valueSwitch2 addTarget:self action:@selector(onSwitch3:) forControlEvents:UIControlEventValueChanged];
    valueSwitch2.on = [[WFCCIMService sharedWFCIMService] isBlackListed:self.userId];
    valueSwitch2.onTintColor = [UIColor colorWithHexExtendString:@"#016EFF"];

    
    
    [self showSeparatorLine:cell4Section1];

    [self.cells addObject:@[cell4Section1].mutableCopy];

    
    
    self.sendMessageCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    for (UIView *subView in self.sendMessageCell.subviews) {
        [subView removeFromSuperview];
    }
    UIButton *btnse = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, 50)];
//    [btnse setImage:[[WFCUImage imageNamed:@"message"] imageWithChangeColor:[UIColor colorWithHexString:@"#016EFF"]] forState:UIControlStateNormal];
//    btnse.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
    [btnse setTitle:WFCString(@"SendMessage") forState:UIControlStateNormal];
    [btnse setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
    btnse.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [btnse addTarget:self action:@selector(onSendMessageBtn:) forControlEvents:UIControlEventTouchDown];
    if (@available(iOS 14, *)) {
        [self.sendMessageCell.contentView addSubview:btnse];
    } else {
        [self.sendMessageCell addSubview:btnse];
    }
    
    self.addFriendCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    for (UIView *subView in self.addFriendCell.subviews) {
        [subView removeFromSuperview];
    }
    UIButton *btnAdd = [[UIButton alloc] initWithFrame:CGRectMake(20, 0, width - 40, 50)];
    [btnAdd setTitle:WFCString(@"DeleteFriend") forState:UIControlStateNormal];
    //            [btn setBackgroundColor:/*[UIColor colorWithHexString:@"#016EFF"]*/];
    [btnAdd addTarget:self action:@selector(onAddFriendBtn:) forControlEvents:UIControlEventTouchDown];
    //            btn.layer.cornerRadius = 5.f;
    btnAdd.layer.masksToBounds = YES;
    btnAdd.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    
    [btnAdd setTitleColor:[UIColor redColor] forState:0];
    if (@available(iOS 14, *)) {
        [self.addFriendCell.contentView addSubview:btnAdd];
    } else {
        [self.addFriendCell addSubview:btnAdd];
    }
    
    [self.cells addObject:@[self.sendMessageCell,self.addFriendCell].mutableCopy];

    
    
    
    
//    if (self.userInfo.type == 1) {
//        [self setupSendMessageCell:width];
//    } else {
//        if ([[WFCCIMService sharedWFCIMService] isMyFriend:self.userId]) {
//           
//        }
//        
//        if (self.fromConversation.type == Group_Type) {
//            self.userMessagesCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
//            self.userMessagesCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            if([self.userId isEqualToString:[WFCCNetworkService sharedInstance].userId]) {
//                self.userMessagesCell.textLabel.text = WFCString(@"MyMessages");
//            } else {
//                self.userMessagesCell.textLabel.text = WFCString(@"He`sMessages");
//            }
//            [self.cells addObject:self.userMessagesCell];
//        }
//        
//        if (self.userInfo.type == 0) {
//            if(NSClassFromString(@"SDTimeLineTableViewController")) {
//                self.momentCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"momentCell"];
//                for (UIView *subView in self.momentCell.subviews) {
//                    [subView removeFromSuperview];
//                }
//                
//                UIButton *momentButton = [[UIButton alloc] initWithFrame:CGRectMake(16, 0, self.view.frame.size.width - 100, 70)];
//                [momentButton setTitle: @"朋友圈" forState:UIControlStateNormal];
//                [momentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//                momentButton.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
//                momentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//                [momentButton addTarget:self action:@selector(momentClick) forControlEvents:UIControlEventTouchUpInside];
//                if (@available(iOS 14, *)) {
//                    [self.momentCell.contentView addSubview:momentButton];
//                } else {
//                    [self.momentCell addSubview:momentButton];
//                }
//                self.momentCell.selectionStyle = UITableViewCellSelectionStyleNone;
//                self.momentCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            }
//        }
//        
//        if ([[WFCCIMService sharedWFCIMService] isMyFriend:self.userId]) {
//            [self setupSendMessageCell:width];
//            [self showSeparatorLine:self.sendMessageCell];
//            
//#if WFCU_SUPPORT_VOIP
//            self.voipCallCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
//            for (UIView *subView in self.voipCallCell.subviews) {
//                [subView removeFromSuperview];
//            }
//            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, 50)];
//            [btn setImage:[[WFCUImage imageNamed:@"video"] imageWithChangeColor:[UIColor colorWithHexString:@"#016EFF"]] forState:UIControlStateNormal];
//            btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
//            [btn setTitle:WFCString(@"VOIPCall") forState:UIControlStateNormal];
//            [btn addTarget:self action:@selector(onVoipCallBtn:) forControlEvents:UIControlEventTouchDown];
//            [btn setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
//            btn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleMedium size:16];
//            if (@available(iOS 14, *)) {
//                [self.voipCallCell.contentView addSubview:btn];
//            } else {
//                [self.voipCallCell addSubview:btn];
//            }
//#endif
//        } else if([[WFCCNetworkService sharedInstance].userId isEqualToString:self.userId]) {
//            
//        } else {
//            self.addFriendCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
//            for (UIView *subView in self.addFriendCell.subviews) {
//                [subView removeFromSuperview];
//            }
//            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(20, 0, width - 40, 50)];
//            [btn setTitle:WFCString(@"AddFriend") forState:UIControlStateNormal];
//            //            [btn setBackgroundColor:/*[UIColor colorWithHexString:@"#016EFF"]*/];
//            [btn addTarget:self action:@selector(onAddFriendBtn:) forControlEvents:UIControlEventTouchDown];
//            //            btn.layer.cornerRadius = 5.f;
//            btn.layer.masksToBounds = YES;
//            btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
//            
//            [btn setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:0];
//            if (@available(iOS 14, *)) {
//                [self.addFriendCell.contentView addSubview:btn];
//            } else {
//                [self.addFriendCell addSubview:btn];
//            }
//            if(self.fromConversation.type == Group_Type) {
//                WFCCGroupInfo *groupInfo = [[WFCCIMService sharedWFCIMService] getGroupInfo:self.fromConversation.target refresh:NO];
//                if(!groupInfo.privateChat) {
//                    [self setupSendMessageCell:width];
//                }
//            }
//        }
//    }
    
    [self.tableView reloadData];
}

-(void)ClearChatHistory{
     
    
    __weak typeof(self)ws = self;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    UIAlertAction *aliasAction = [UIAlertAction actionWithTitle:WFCString(@"ClearChatHistory") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        
           WFCCConversation *con = [WFCCConversation conversationWithType:Single_Type target:self.userId line:0];
           
       //    [[WFCCIMService sharedWFCIMService] clearMessages:con  ];
           
           [[WFCCIMService sharedWFCIMService] removeConversation:con clearMessage:YES];

           
           MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
           hud.mode = MBProgressHUDModeText;
           hud.label.text = WFCString(@"Deleted");
           //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
           [hud hideAnimated:YES afterDelay:1.f];
            hud.completionBlock = ^{
                [ws.navigationController popToRootViewControllerAnimated:YES ];
            };
           [[NSNotificationCenter defaultCenter] postNotificationName:kMessageListChanged object:con];
           

    }];
    [actionSheet addAction:aliasAction];
     
    
    UIAlertAction *cancelStarActio1n = [UIAlertAction actionWithTitle:WFCString(@"cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                [ws setFavUser];
        
        
    }];
    [actionSheet addAction:cancelStarActio1n];

    [self presentViewController:actionSheet animated:YES completion:nil];
    
}

- (void)setupSendMessageCell:(CGFloat)width {
    self.sendMessageCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    for (UIView *subView in self.sendMessageCell.subviews) {
        [subView removeFromSuperview];
    }
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, 50)];
//    [btn setImage:[[WFCUImage imageNamed:@"message"] imageWithChangeColor:[UIColor colorWithHexString:@"#016EFF"]] forState:UIControlStateNormal];
//    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10);
    [btn setTitle:WFCString(@"SendMessage") forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [btn addTarget:self action:@selector(onSendMessageBtn:) forControlEvents:UIControlEventTouchDown];
    if (@available(iOS 14, *)) {
        [self.sendMessageCell.contentView addSubview:btn];
    } else {
        [self.sendMessageCell addSubview:btn];
    }
}

- (UITableViewCell *)moreCell {
    if(!_moreCell) {
        _moreCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"more_cell"];

        _moreCell.accessoryType = UITableViewCellAccessoryNone;
        _moreCell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"right_arrow"]];

        _moreCell.textLabel.text = WFCString(@"More");
    }
    return _moreCell;
}

- (UIEdgeInsets)hiddenSeparatorLine:(UITableViewCell *)cell {
    return cell.separatorInset = UIEdgeInsetsMake(self.view.frame.size.width, 0, 0, 0);
}

- (void)showSeparatorLine:(UITableViewCell *)cell {
    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)onViewPortrait:(id)sender {
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    browser.displayNavArrows = NO;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    browser.enableSwipeToDismiss = NO;
    browser.autoPlayOnAppear = NO;
    [browser setCurrentPhotoIndex:0];
    [self.navigationController pushViewController:browser animated:YES];
}

- (void)momentClick {
    
    
    //    Class cls = NSClassFromString(@"SDTimeLineTableViewController");
    //    UIViewController *vc = [[WFCUFCircleVC alloc] init];
    //    [vc performSelector:@selector(setUserId:) withObject:self.userId];
    //    [self.navigationController pushViewController:vc animated:YES];
}


- (void)onSendMessageBtn:(id)sender {
    WFCUMessageListViewController *mvc = [[WFCUMessageListViewController alloc] init];
    mvc.conversation = [WFCCConversation conversationWithType:Single_Type target:self.userId line:0];
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[WFCUMessageListViewController class]]) {
            WFCUMessageListViewController *old = (WFCUMessageListViewController*)vc;
            if (old.conversation.type == Single_Type && [old.conversation.target isEqualToString:self.userId]) {
                [self.navigationController popToViewController:vc animated:YES];
                return;
            }
        }
    }
    UINavigationController *nav = self.navigationController;
    [self.navigationController popToRootViewControllerAnimated:NO];
    mvc.hidesBottomBarWhenPushed = YES;
    [nav pushViewController:mvc animated:YES];
}

- (void)onVoipCallBtn:(id)sender {
#if WFCU_SUPPORT_VOIP
    __weak typeof(self)ws = self;
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *actionVoice = [UIAlertAction actionWithTitle:WFCString(@"VoiceCall") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WFCCConversation *conversation = [WFCCConversation conversationWithType:Single_Type target:ws.userInfo.userId line:0];
        [self startCall:@[ws.userInfo.userId] isMulti:NO conversation:conversation audioOnly:YES];
    }];
    
    UIAlertAction *actionVideo = [UIAlertAction actionWithTitle:WFCString(@"VideoCall") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        WFCCConversation *conversation = [WFCCConversation conversationWithType:Single_Type target:ws.userInfo.userId line:0];
        [self startCall:@[ws.userInfo.userId] isMulti:NO conversation:conversation audioOnly:NO];
    }];
    
    //把action添加到actionSheet里
    [actionSheet addAction:actionVoice];
    [actionSheet addAction:actionVideo];
    [actionSheet addAction:actionCancel];
    
    
    //相当于之前的[actionSheet show];
    [self presentViewController:actionSheet animated:YES completion:nil];
#endif
}

#if WFCU_SUPPORT_VOIP
- (void)startCall:(NSArray<NSString *> *)targetIds isMulti:(BOOL)isMulti conversation:(WFCCConversation *)conversation audioOnly:(BOOL)isAudioOnly {
    [WFCUUtilities checkRecordOrCameraPermission:YES complete:^(BOOL granted) {
        if(granted) {
            if(isAudioOnly) {
                UIViewController *videoVC;
                if(isMulti) {
                    videoVC = [[WFCUMultiVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
                } else {
                    videoVC = [[WFCUVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
                }
                [[WFAVEngineKit sharedEngineKit] presentViewController:videoVC];
            } else {
                [WFCUUtilities checkRecordOrCameraPermission:NO complete:^(BOOL granted) {
                    if(granted) {
                        UIViewController *videoVC;
                        if(isMulti) {
                            videoVC = [[WFCUMultiVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
                        } else {
                            videoVC = [[WFCUVideoViewController alloc] initWithTargets:targetIds conversation:conversation audioOnly:isAudioOnly];
                        }
                        [[WFAVEngineKit sharedEngineKit] presentViewController:videoVC];
                    }
                } viewController:self];
            }
        }
    } viewController:self];
}
#endif

- (void)onAddFriendBtn:(id)sender {
//    WFCUVerifyRequestViewController *vc = [[WFCUVerifyRequestViewController alloc] init];
//    vc.userId = self.userId;
//    vc.sourceType = self.sourceType;
//    vc.sourceTargetId = self.sourceTargetId;
//    [self.navigationController pushViewController:vc animated:YES];
    
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  
    __weak typeof(self)ws = self;

    
    
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:WFCString(@"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [actionSheet addAction:actionCancel];
    UIAlertAction *deleteFriendAction = [UIAlertAction actionWithTitle:WFCString(@"DeleteFriend") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
        hud.label.text = WFCString(@"Processing");
        [hud showAnimated:YES];
        
        [[WFCCIMService sharedWFCIMService] deleteFriend:ws.userId success:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessDone");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
                hud.completionBlock = ^{
                    [ws.navigationController popToRootViewControllerAnimated:YES];
                };
            });
            
        } error:^(int error_code) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessFailure");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            });
        }];
    }];
    
    [actionSheet addAction:deleteFriendAction];
    [self presentViewController:actionSheet animated:YES completion:nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource<NSObject>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.cells[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"section:%ld",(long)indexPath.section);
    return self.cells[indexPath.section][indexPath.row];

//    if (indexPath.section == 0) {
//        return self.headerCells[indexPath.row];
//    } else if (indexPath.section == 1) {
//        if(self.momentCell && indexPath.row == 0) {
//            return self.momentCell;
//        }
//        
//        int index = indexPath.row;
//        if(self.momentCell)
//            index--;
//        
//        if(index < self.organizationIds.count) {
//            NSInteger orgId = [self.organizationIds[index] integerValue];
//            WFCUOrganization *org = [[WFCUOrganizationCache sharedCache] getOrganization:orgId refresh:NO];
//            
//            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"org_cell"];
//            if(!cell) {
//                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"org_cell"];
//            }
//            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            cell.textLabel.text = @"部门";
//            cell.detailTextLabel.text = org.name;
//            return cell;
//        } else {
//            return self.moreCell;
//        }
//    } else if (indexPath.section == 2) {
//        return self.cells[indexPath.row];
//    } else {
//        if (self.sendMessageCell) {
//            if (indexPath.row == 0) {
//                return self.sendMessageCell;
//            } else if(indexPath.row == 1) {
//                if(self.voipCallCell) {
//                    return self.voipCallCell;
//                }
//            }
//            return self.addFriendCell;
//        } else {
//            return self.addFriendCell;
//        }
//    }
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cells.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section != 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 10)];
        view.backgroundColor = [WFCUConfigManager globalManager].backgroudColor;
        return view;
    } else {
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 10;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @" ";
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if([tableView cellForRowAtIndexPath:indexPath] == self.userMessagesCell) {
        WFCUUserMessageListViewController *vc = [[WFCUUserMessageListViewController alloc] init];
        vc.userId = self.userId;
        vc.conversation = self.fromConversation;
        [self.navigationController pushViewController:vc animated:YES];
    } else if([tableView cellForRowAtIndexPath:indexPath] == self.moreCell) {
        WFCUProfileMoreTableViewController *moreVC = [[WFCUProfileMoreTableViewController alloc] init];
        moreVC.userId = self.userId;
        [[WFCCIMService sharedWFCIMService] getCommonGroups:self.userId success:^(NSArray<NSString *> *groupIds) {
            moreVC.commonGroupIds = groupIds;
        } error:^(int error_code) {
            
        }];
        [self.navigationController pushViewController:moreVC animated:YES];
    } else if(indexPath.section == 1) {
        if(self.momentCell && indexPath.row == 0) {
            //click momentCell
        }
        
        int index = (int)indexPath.row;
        if(self.momentCell)
            index--;
        
        if(index < self.organizationIds.count) {
            NSInteger orgId = [self.organizationIds[index] integerValue];
            NSArray<WFCUOrgRelationship *> *rs = [[WFCUOrganizationCache sharedCache] getRelationship:self.userId refresh:YES];
            __block NSInteger index = orgId;
            NSMutableArray *ids = [[NSMutableArray alloc] init];
            while (index) {
                [ids insertObject:@(index) atIndex:0];
                [rs enumerateObjectsUsingBlock:^(WFCUOrgRelationship * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if(obj.organizationId == index) {
                        index = obj.parentOrganizationId;
                        *stop = YES;
                    }
                }];
            }
            WFCUOrganizationViewController *orgVC = [[WFCUOrganizationViewController alloc] init];
            orgVC.organizationIds = ids;
            orgVC.hidesBottomBarWhenPushed = YES;
            orgVC.isPushed = YES;
            [self.navigationController pushViewController:orgVC animated:YES];
        }
    }
}
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 100;
        } else {
            return 50;
        }
    }  else {
        return 50;
    }
}

- (void)setFriendNote {
    WFCUGeneralModifyViewController *gmvc = [[WFCUGeneralModifyViewController alloc] init];
    NSString *previousAlias = [[WFCCIMService sharedWFCIMService] getFriendAlias:self.userId];
    gmvc.defaultValue = previousAlias;
    gmvc.titleText = @"设置备注";
    gmvc.canEmpty = YES;
    __weak typeof(self)ws = self;
    gmvc.tryModify = ^(NSString *newValue, void (^result)(BOOL success)) {
        if (![newValue isEqualToString:previousAlias]) {
            [[WFCCIMService sharedWFCIMService] setFriend:self.userId alias:newValue success:^{
                result(YES);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [ws loadData];
                });
            } error:^(int error_code) {
                result(NO);
            }];
        }
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:gmvc];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)setFavUser:(UISwitch *)btn {
//    BOOL isFav = [[WFCCIMService sharedWFCIMService] isFavUser:self.userId];
//    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = WFCString(@"Processing");
    [hud showAnimated:YES];
    __weak typeof(self)ws = self;
//    [[WFCCIMService sharedWFCIMService] setFavUser:self.userId fav:!isFav success:^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [hud hideAnimated:YES];
//            
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.mode = MBProgressHUDModeText;
//            hud.label.text = WFCString(@"ProcessDone");
//            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
//            [hud hideAnimated:YES afterDelay:1.f];
//            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [ws loadData];
//            });
//        });
//    } error:^(int errorCode) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [hud hideAnimated:YES];
//            
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//            hud.mode = MBProgressHUDModeText;
//            hud.label.text = WFCString(@"ProcessFailure");
//            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
//            [hud hideAnimated:YES afterDelay:1.f];
//        });
//    }];
    
    
    WFCCConversation *con = [WFCCConversation conversationWithType:Single_Type target:self.userId line:0];

    if (btn.on) {
        [[WFCCIMService sharedWFCIMService] setConversation:con top:1 success:^{
           
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessDone");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [ws loadData];
                });
            });
        } error:^(int error_code) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:NO];
            hud.label.text = WFCString(@"UpdateFailure");
            hud.mode = MBProgressHUDModeText;
            hud.removeFromSuperViewOnHide = YES;
            [hud hideAnimated:NO afterDelay:1.5];
        }];
    }else{
        [[WFCCIMService sharedWFCIMService] setConversation:con top:0 success:^{
            
             dispatch_async(dispatch_get_main_queue(), ^{
                 [hud hideAnimated:YES];
                 
                 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                 hud.mode = MBProgressHUDModeText;
                 hud.label.text = WFCString(@"ProcessDone");
                 //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                 [hud hideAnimated:YES afterDelay:1.f];
                 
                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                     [ws loadData];
                 });
             });
            
        } error:^(int error_code) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:NO];
            hud.label.text = WFCString(@"UpdateFailure");
            hud.mode = MBProgressHUDModeText;
            hud.removeFromSuperViewOnHide = YES;
            [hud hideAnimated:NO afterDelay:1.5];
        }];
        
 
    }
//    UITableViewRowAction *setTop = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:WFCString(@"Pinned") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        [[WFCCIMService sharedWFCIMService] setConversation:ws.conversations[indexPath.row].conversation top:1 success:^{
//            [ws refreshList];
//        } error:^(int error_code) {
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:NO];
//            hud.label.text = WFCString(@"UpdateFailure");
//            hud.mode = MBProgressHUDModeText;
//            hud.removeFromSuperViewOnHide = YES;
//            [hud hideAnimated:NO afterDelay:1.5];
//        }];
//    }];
//    
//    UITableViewRowAction *setUntop = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:WFCString(@"Unpinned") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        [[WFCCIMService sharedWFCIMService] setConversation:ws.conversations[indexPath.row].conversation top:0 success:^{
//            [ws refreshList];
//        } error:^(int error_code) {
//            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:NO];
//            hud.label.text = WFCString(@"UpdateFailure");
//            hud.mode = MBProgressHUDModeText;
//            hud.removeFromSuperViewOnHide = YES;
//            [hud hideAnimated:NO afterDelay:1.5];
//        }];
//        
//        [self refreshList];
//    }];
    
}

- (void)onSwitch4:(UISwitch *)btn {
    __weak typeof(self)ws = self;

    WFCCConversation *con = [WFCCConversation conversationWithType:Single_Type target:self.userId line:0];
 
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
    hud.label.text = WFCString(@"Processing");
    [hud showAnimated:YES];

    
    [[WFCCIMService sharedWFCIMService] setConversation:con silent:btn.on success:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [hud hideAnimated:YES];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = WFCString(@"ProcessDone");
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [ws loadData];
            });
        });
        
    }   error:^(int error_code) {
        [hud hideAnimated:YES];
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = WFCString(@"ProcessFailure");
        //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
        [hud hideAnimated:YES afterDelay:1.f];
    }];
    
}


- (void)onSwitch3:(UISwitch *)btn {
    
    __weak typeof(self)ws = self;

    
    if ([[WFCCIMService sharedWFCIMService] isBlackListed:self.userId]) {

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
        hud.label.text = WFCString(@"Processing");
        [hud showAnimated:YES];
        
        [[WFCCIMService sharedWFCIMService] setBlackList:ws.userId isBlackListed:NO success:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessDone");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [ws loadData];
                });
            });
        } error:^(int error_code) {
            [hud hideAnimated:YES];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = WFCString(@"ProcessFailure");
            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
        }];
        
    } else  {  //Only normal user can add to blacklist, robot user not allowed.

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
        hud.label.text = WFCString(@"Processing");
        [hud showAnimated:YES];
            
        [[WFCCIMService sharedWFCIMService] setBlackList:ws.userId isBlackListed:YES success:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessDone");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [ws loadData];
                });
            });
            
        } error:^(int error_code) {
                [hud hideAnimated:YES];
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:ws.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.label.text = WFCString(@"ProcessFailure");
                //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
                [hud hideAnimated:YES afterDelay:1.f];
            }];
        };
 
    
}


#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return 1;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:self.userInfo.portrait]];
    return photo;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    return nil;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
    NSLog(@"Did start viewing photo at index %lu", (unsigned long)index);
}

- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
    return NO;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
    NSLog(@"Photo at index %lu selected %@", (unsigned long)index, selected ? @"YES" : @"NO");
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
    // If we subscribe to this method we must dismiss the view controller ourselves
    NSLog(@"Did finish modal presentation");
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
